#!/bin/bash

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/common.sh"

function set_dir() {
  EXPECTED_DIR="${SCRIPT_DIR}/Expected" || return 1
  PRACTICAL_DIR="${SCRIPT_DIR}/Practical" || return 1
  TEST_CASE_DIR="${SCRIPT_DIR}/TestCase" || return 1
}

function comparison_of_quantification_results() {
  # The ignored fields "start_time" and "call" are related to the command execution time stop and parameter path, not due to feature comparison
  diff <(sed '11,12d' "$1/run_info.json") <(sed '11,12d' "$2/run_info.json") >/dev/null || return 1
  # Mainly ignore the difference between the generated HDF5 file path, the absolute path of the executed command and the time stamp.
  diff <(sed '1d;428d;435d;570d;571d' "$1/abundance.h5.ali") <(sed '1d;428d;435d;570d;571d' "$2/abundance.h5.ali") >/dev/null || return 1
  diff "$1/abundance.tsv" "$2/abundance.tsv" >/dev/null || return 1
}

function visualize_the_pseudoalignments_comparison_of_results() {
  comparison_of_quantification_results "$1" "$2" || return 1
  cmp "$1/pseudoalignments.bam" "$2/pseudoalignments.bam" >/dev/null || return 1
  cmp "$1/pseudoalignments.bam.bai" "$2/pseudoalignments.bam.bai" >/dev/null || return 1
}

function start_test() {
  compare_file_content_by_diff "$1/kallistoUsage" "$2/kallistoUsage" \
    "kallisto" || return 1

  compare_file_content_by_cmp "$1/transcripts.idx" "$2/transcripts.idx" \
    "kallisto index -i transcripts.idx transcripts.fasta.gz" || return 1

  comparison_of_quantification_results "$1/outputQuantification" "$2/outputQuantification"
  print_execution_result "$?" "kallisto quant -i transcripts.idx -o output -b 100 reads_1.fastq.gz reads_2.fastq.gz" || return 1

  comparison_of_quantification_results "$1/outputSingleEndReads" "$2/outputSingleEndReads"
  print_execution_result "$?" "kallisto quant -i transcripts.idx -o output -b 100 --single -l 180 -s 20 reads_1.fastq.gz" || return 1

  visualize_the_pseudoalignments_comparison_of_results "$1/outputGenomebam" "$2/outputGenomebam"
  print_execution_result "$?" "kallisto quant -i transcripts.kidx -b 30 -o kallisto_out --genomebam --gtf transcripts.gtf.gz --chromosomes chrom.txt reads_1.fastq.gz reads_2.fastq.gz" || return 1
}

function test_clean() {
  for i in "$@"; do
    delete_a_directory_or_file "$i"
  done
}

function main() {
  is_expected_architecture aarch64 || return 1
  set_script_dir || return 1
  set_dir || return 1
  conda_initialize "$1"
  create_and_activate_conda_env local || return 1
  generate_HDF5_intermediate_alignment_files "${EXPECTED_DIR}" "${PRACTICAL_DIR}" || return 1
  start_test "${EXPECTED_DIR}" "${PRACTICAL_DIR}"
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;5mThe test was successful.\n\033[0m"
  else
    echo -e "\033[1;31;1mTest failed.\n\033[0m"
  fi
  test_clean "${TEST_CASE_DIR}" "${EXPECTED_DIR}" "${PRACTICAL_DIR}" || return 1
}

# /bin/bash ~/hpc/Anaconda/bioconda/kallisto/0.48.0/h0d531b0_1/test/generate_practical_data.sh /root/anaconda3
main "$@"
